<template>
  <p-card :bordered="false" class="containent">
    <div class="table-page-search-wrapper wrap1">
      <p-row type="flex" justify="space-between">
        <p-col span="16">
          <p-form-model layout="inline" :model="topForm" :rules="rules">
            <p-row :gutter="24">
              <p-col :xl="9" :lg="7" :md="8" :sm="24">
                <p-form-model-item label="条码扫描">
                  <p-input
                    placeholder="请扫描"
                    @change="changScan"
                    @focus="focus"
                    v-model.trim="scan"
                  ></p-input>
                </p-form-model-item>
              </p-col>
              <p-col :xl="7" :lg="7" :md="8" :sm="24">
                <p-form-model-item label="线体">
                  <p-select
                    v-model="topForm.lineno"
                    @change="changeLine"
                    allowClear
                  >
                    <p-select-option
                      v-for="item in lines"
                      :key="item.codeValue"
                      :value="item.codeValue"
                      >{{ item.textValue }}</p-select-option
                    >
                  </p-select>
                </p-form-model-item>
              </p-col>
              <p-col :xl="7" :lg="7" :md="8" :sm="24">
                <p-form-model-item label="工站">
                  <p-tree-select
                    v-model="topForm.stationCode"
                    :tree-data="stations"
                    :dropdown-style="{ maxHeight: '500px' }"
                    tree-node-filter-prop="title"
                    show-search
                    allow-clear
                    tree-default-expand-all
                    @change="changeHandler"
                  />
                </p-form-model-item>
              </p-col>
            </p-row>
          </p-form-model>
        </p-col>
        <p-col>
          <p-button type="primary" @click="path('/work/datacollect/Processkey')"
            >关键件采集</p-button
          >
          <p-button
            type="primary"
            style="margin: 0 10px 0 10px"
            @click="path('/work/datacollect/Packaging')"
            >包装采集</p-button
          >
          <p-button type="primary" @click="path('/work/datacollect/Startaging')"
            >老化采集</p-button
          >
        </p-col>
      </p-row>
      <div class="table-operator text-right">
        <p-radio-group
          :value="currentView"
          button-style="solid"
          @change="setCurrentView"
        >
          <p-radio-button value="spot-check">开线点检</p-radio-button>
          <p-radio-button value="sop">SOP</p-radio-button>
          <p-radio-button value>数据采集</p-radio-button>
          <p-radio-button value="first-check">首检</p-radio-button>
          <p-radio-button value>工序采集</p-radio-button>
          <p-radio-button value>生产异常</p-radio-button>
          <p-radio-button value>工序交接</p-radio-button>
          <p-radio-button value>在线送修</p-radio-button>
        </p-radio-group>
      </div>
      <div class="content">
        <!-- <div
          class="icon"
          @click="changicon(!expand)"
          :style="{ left: expand ? null : 0 }"
        >
          <p-icon :type="expand ? 'left' : 'right'" />
        </div> -->
        <div class="list1" :class="{ unshow: !expand }">
          <Order
            @on-item-click="post"
            :params="topForm"
            v-show="expand"
          ></Order>
        </div>
        <div class="tab">
          <p-row type="flex" justify="space-between">
            <p-col>
              <span style="display: block; font-weight: 800; margin-bottom: 5px"
                >条码信息</span
              >
            </p-col>
          </p-row>
          <!-- 关键数量模块 -->
          <p-row type="flex" justify="space-between">
            <p-col :span="9">
              <div class="left_list">
                <p-form :layout="horizontal">
                  <p-form-item>
                    <p-input placeholder="带出当前扫码的产品SN" />
                  </p-form-item>
                  <p-form-item>
                    <p-input
                      placeholder="带出当前扫码的关键件条码信息"
                      v-model.trim="SN"
                    />
                  </p-form-item>
                </p-form>
                <div class="operator">
                  <p-button type="primary" @click="bind">绑定</p-button>
                  <p-button type="primary" @click="reload">重新开始</p-button>
                </div>
              </div>
            </p-col>
            <p-col
              :span="14"
              style="
                height: 230px;
                border: 1px solid #eee;
                line-height: 40px;
                padding: 10px 20px 0px 20px;
              "
            >
              <!-- 右上侧Table区域 -->
              <p-form layout="inline">
                <p-row :gutter="24">
                  <p-col :xl="12">
                    <p-form-item label="工序单号">
                      <p-input readOnly v-model="form.processBillNo"></p-input>
                    </p-form-item>
                  </p-col>
                  <p-col :xl="12">
                    <p-form-item label="产品编码">
                      <p-input readOnly v-model="form.productcode"></p-input>
                    </p-form-item>
                  </p-col>
                  <!-- <p-col :xl="6">
                    <p-form-item label="产品描述">
                      <p-input readOnly v-model="form.productname"></p-input>
                    </p-form-item>
                  </p-col>
                  <p-col :xl="6">
                    <p-form-item label="工单数量">
                      <p-input readOnly v-model="form.planQty"></p-input>
                    </p-form-item>
                  </p-col> -->
                </p-row>
              </p-form>
              <div style="height: 45px">
                <p-alert
                  v-if="visible"
                  message="关键件绑定完成"
                  type="success"
                  closable
                  :after-close="handleClose"
                />
              </div>
              <div>
                <p-col :span="8" style="padding: 0px 20px">
                  <p-row :span="24">
                    <div class="num">
                      <div class="num_item">关键件数量</div>
                      <div class="num_item">{{ columnsData.length }}</div>
                    </div>
                  </p-row>
                </p-col>
                <p-col :span="8" style="padding: 0px 20px">
                  <p-row :span="24">
                    <div class="num" style="background: #006666">
                      <div class="num_item">已采集数量</div>
                      <div class="num_item">{{ finshed }}</div>
                    </div>
                  </p-row>
                </p-col>
                <p-col :span="8" style="padding: 0px 20px">
                  <p-row :span="24">
                    <div class="num" style="background: #3333ff">
                      <div class="num_item">待采集数量</div>
                      <div class="num_item">
                        {{ columnsData.length - finshed }}
                      </div>
                    </div>
                  </p-row>
                </p-col>
              </div>
            </p-col>
          </p-row>
          <!-- 底部表格 -->
          <p-row
            type="flex"
            justify="space-between"
            style="margin-top: 20px"
            class="bottom-form"
          >
            <!-- 采集记录 -->
            <p-col
              span="9"
              style="height: 100%; display: flex; flex-direction: column"
            >
              <div>
                <span
                  style="display: block; font-weight: 800; margin-bottom: 5px"
                  >采集记录</span
                >
              </div>
              <div class="caiji">
                <p-table
                  ref="table"
                  size="middle"
                  bordered
                  :pagination="false"
                  rowKey="id"
                  :columns="columns"
                  :dataSource="columnsData"
                  :loading="loadingGet"
                  @change="handleTableChange"
                  :scroll="tableScroll1"
                >
                  <template slot="status" slot-scope="text, record">
                    <p-tag v-if="record.result" color="#4064E9">采集成功</p-tag>
                    <p-tag v-else color="#999">未采集</p-tag>
                  </template>
                </p-table>
              </div>
            </p-col>
            <!-- 右表 -->
            <p-col
              span="14"
              style="height: 100%; display: flex; flex-direction: column"
            >
              <p-radio-group :value="bd" @change="handleSizeChange2">
                <p-radio-button value="bind">绑定记录</p-radio-button>
                <p-radio-button value="replace">关键件替换记录</p-radio-button>
              </p-radio-group>
              <div class="bangding">
                <p-table
                  v-if="tags"
                  ref="table"
                  size="middle"
                  bordered
                  rowKey="id"
                  :columns="columnsBind"
                  :dataSource="bindrecordData"
                  :loading="loading"
                  @change="handleTableChange"
                  :scroll="tableScroll"
                  :pagination="false"
                >
                  <template slot="replace" slot-scope="text, record">
                    <p-button type="primary" @click="replaceHandler(record)"
                      >替换</p-button
                    >
                  </template>
                </p-table>
                <p-table
                  v-else
                  ref="table"
                  size="middle"
                  bordered
                  rowKey="id"
                  :columns="columnsReplace"
                  :dataSource="replaceData"
                  :loading="loadingReplace"
                  @change="handleTableChange"
                  :scroll="tableScroll"
                  :pagination="false"
                >
                  <template slot="replace" slot-scope="text, record">
                    <p-button type="primary" @click="replaceHandler(record)"
                      >替换</p-button
                    >
                  </template>
                </p-table>
              </div>
            </p-col>
          </p-row>
        </div>
      </div>
      <!-- 弹出窗 -->
      <ReplaceModal ref="modalForm" @ok="okRefresh"></ReplaceModal>
    </div>
  </p-card>
</template>

<script>
import { api } from "@/api/manage";
import { filterObj, timestampToDatetime } from "@/utils/util";
import Vue from "vue";
import { postAction, getAction, deleteAction, httpAction } from "@/api/manage";
import ReplaceModal from "./modules/ReplaceModal";
import pick from "lodash.pick";
import Order from "@/views/work/productionExecution/components/order.vue";
import { Loading } from "vant";
import mixins from "./modules/line-station";

//采集记录表
const columns = [
  {
    title: "序号",
    dataIndex: "",
    key: "rowIndex",
    width: 50,
    align: "center",
    customRender: function (t, r, index) {
      return parseInt(index) + 1;
    },
  },
  {
    title: "关键物料编码",
    align: "center",
    dataIndex: "mcode",
  },
  {
    title: "关键物料描述",
    align: "center",
    dataIndex: "mname",
  },
  {
    title: "采集结果",
    align: "center",
    dataIndex: "result",
    scopedSlots: { customRender: "status" },
  },
];
//绑定记录表头
const Binding_record = [
  {
    title: "序号",
    dataIndex: "",
    key: "rowIndex",
    width: 60,
    align: "center",
    customRender: function (t, r, index) {
      return parseInt(index) + 1;
    },
  },
  {
    title: "线体",
    align: "center",
    dataIndex: "linename",
  },
  {
    title: "工站",
    align: "center",
    dataIndex: "workstationName",
  },
  {
    title: "工序工单",
    align: "center",
    dataIndex: "mobillno",
  },
  {
    title: "产品编码",
    align: "center",
    dataIndex: "productCode",
  },
  {
    title: "产品数量",
    align: "center",
    dataIndex: "productQty",
  },
  {
    title: "关键物料编码",
    align: "center",
    dataIndex: "barCode",
  },
  {
    title: "关键物料描述",
    align: "center",
    dataIndex: "mname",
  },
  {
    title: "绑定数量",
    align: "center",
    dataIndex: "bindingQuantity",
  },
  {
    title: "操作人员",
    align: "center",
    dataIndex: "optname",
  },
  {
    title: "操作",
    align: "center",
    dataIndex: "productLine",
    width: 60,
    fixed: "right",
    scopedSlots: { customRender: "replace" },
  },
];
//关键件替换记录表头
const Replace_record = [
  {
    title: "序号",
    dataIndex: "",
    key: "rowIndex",
    width: 60,
    align: "center",
    customRender: function (t, r, index) {
      return parseInt(index) + 1;
    },
  },
  {
    title: "线体",
    align: "center",
    dataIndex: "linename",
  },
  {
    title: "工站",
    align: "center",
    dataIndex: "workstationName",
  },
  {
    title: "工序工单",
    align: "center",
    dataIndex: "mobillno",
  },
  {
    title: "产品编码",
    align: "center",
    dataIndex: "productCode",
  },
  {
    title: "产品数量",
    align: "center",
    dataIndex: "productQty",
  },
  {
    title: "关键物料描述",
    align: "center",
    dataIndex: "mname",
  },
  {
    title: "关键物料条码(旧)",
    align: "center",
    dataIndex: "bindingFormer",
  },
  {
    title: "关键物料条码(新)",
    align: "center",
    dataIndex: "bindingNew",
  },
  {
    title: "替换人员",
    align: "center",
    dataIndex: "displacedPerson",
  },
];
export default {
  name: "Processkey",
  mixins: [mixins],
  components: {
    ReplaceModal,
    Order,
  },
  data() {
    return {
      url: {
        list: "/mes-craft/craft/mesPeProcessRoute/list",
        delete: "/mes-craft/craft/mesPeProcessRoute/delete",
        deleteBatch: "/mes-craft/craft/mesPeProcessRoute/deleteBatch",
        exportXlsUrl: "/mes-code/mesBcTemplate/export",
        // importExcelUrl: '/mes-code/auto/mesBcTemplate/importExcel',
        getColumns: "/mes-code/online/cgform/api/getColumns/",
        buttonAction: "/mes-code/online/cgform/api/doButton",
        getbind_record:
          "/mes-manufacture/mfBindingRecord/getBindRecordByProcessBillNo", //获取当前绑定记录
        getreplace_record:
          "/mes-manufacture/mfProcessCriticalComponentBinding/getKeyMaterialBindExchangeByProcessBillNo/", //获取替换记录表
        bind: "/mes-manufacture/mfBindingRecord/saveKeyMaterielBind", //实现绑定
        getcolumns: "/mes-craft/craft/mesPeProcessRoute/getBomInfoByCode", //根据工艺路线编码获得关键物料
        replace: "/mes-manufacture/mfProcessCriticalComponentBinding", //实现替换
        getGxgd: "/mes-manufacture/mfStartWork/getProcessbillNoList", //获得工序工单
        judgeBindRecord: "/mes-manufacture/mfBindingRecord/getBindRecordFlag", //判断是否做过绑定
      },
      bd: "bind",
      gj: "e",
      dictOptions: {},
      size: "a",
      columns: [], //条码信息表格
      columnsBind: [], //绑定记录表
      columnsReplace: [], //替换记录记录表
      bindrecordData: [],
      replaceData: [],
      tags: true,
      columnsData: [],
      collectData: [],
      visible: false,
      form: {}, //工序工单列表
      SN: "",
      SNall: {},
      loading: false,
      loadingReplace: false,
      loadingGet: false,
      finshed: 0, //已采集
      tableScroll: {
        x: 900,
      },
      tableScroll1: { x: 300 },
      rules: {
        stationCode: [
          { required: true, message: "请选择工站", trigger: "change" },
        ],
      },
      bool: true,
      unshow: false,
      expand: true,
    };
  },
  watch: {
    SN: function (oldVal) {
      this.columnsData.map((item) => {
        let params = {
          mname: item.mname,
          mcode: item.mcode,
          moid: this.form.id,
          recordName: item.mname,
          workstationCode: this.topForm.stationCode,
          result: "",
          workstationName: this.topForm.stationName,
          barCode: oldVal,
          barcodeType: item.maintenanceSap == "SN" ? 1 : 2,
          bindingQuantity: 1,
        };
        if (item.mcode == oldVal) {
          if (this.collectData.length == 0) {
            item.result = true;
            this.collectData.push(params);
            this.finshed++;
          } else {
            let bool = this.collectData.some((items) => items.mcode === oldVal);
            if (!bool) {
              item.result = true;
              this.collectData.push(params);
              this.finshed++;
            } else {
              return this.$message.warning("该条码已被扫描");
            }
          }
        }
      });
    },
    form: function () {
      this.visible = false;
      this.judgeBindRecord();
      this.getBind_recordlist();
      this.getReplace_record();
    },
    columnsData: {
      handler: function (val) {
        let bool = val.some((item) => item.result == false);
        if (!bool) {
          this.bind();
        }
      },
      deep: true,
    },
  },

  created() {
    this.columns = columns;
    this.columnsBind = Binding_record;
    this.columnsReplace = Replace_record;
  },
  methods: {
    handleSizeChange(e) {
      this.size = e.target.value;
    },
    handleSizeChange1(e) {
      this.gj = e.target.value;
    },
    post(s) {
      this.form = s;
    },
    handleClose() {
      this.visible = false;
    },
    //绑定关键物料
    bind() {
      let bool = this.columnsData.some((item) => item.result == false);
      if (!bool) {
        if (this.columnsData.length !== 0) {
          postAction(this.url.bind, this.collectData).then((res) => {
            if (!res.success) return this.$message.warning(res.msg);
            this.visible = true;
            setTimeout(() => {
              this.handleClose();
            }, 2000);
            this.getBind_recordlist();
          });
        }
      } else {
        this.$message.warning("该工单未全部采集完成");
      }

      // }
    },
    changeHandler(val, label) {
      this.topForm.stationName = label[0];
      this.judgeBindRecord();
    },
    //获得绑定记录表
    getBind_recordlist() {
      this.loading = true;
      getAction(this.url.getbind_record + "/" + this.form.processBillNo).then(
        (res) => {
          if (res.success) {
            this.bindrecordData = res.data;
          } else {
            this.$message.warning(res.msg);
          }
          this.loading = false;
        }
      );
    },
    changScan(e) {
      this.SN = e.target.value;
    },
    judgeBindRecord() {
      let params = {
        processBillNo: this.form.processBillNo,
        stationCode: this.topForm.stationCode,
      };
      getAction(this.url.judgeBindRecord, params).then((res) => {
        if (res.data) {
          this.$message.warning("该关键件物料已经完成绑定");
          this.columnsData = [];
        } else {
          this.getColumns();
        }
      });
    },
    //获得采集记录表
    getColumns() {
      let params = {
        routerCode: this.form.processCoding,
        processCode: this.topForm.stationCode,
        version: this.form.processVersion,
        type: 0,
      };
      this.loadingGet = true;
      httpAction(this.url.getcolumns, params, "post")
        .then((res) => {
          if (res.success) {
            this.columnsData = res.data;
            this.columnsData.map((item) => {
              this.$set(item, "result", false);
            });
          } else {
            this.$message.warning(res.msg);
            // this.columnsData = [];
          }
          this.loadingGet = false;
        })
        .finally(() => {
          this.finshed = 0;
          this.SN = "";
          this.collectData = [];
        });
    },
    //获得关键件替换记录表
    getReplace_record() {
      this.loadingReplace = true;
      httpAction(
        this.url.getreplace_record + this.form.processBillNo,
        {},
        "GET"
      ).then((res) => {
        if (res.success) {
          this.replaceData = res.data;
        } else {
          this.$message.warning(res.msg);
        }
        this.loadingReplace = false;
      });
    },
    //tap切换函数（绑定记录和关键件记录切换）
    handleSizeChange2(e) {
      let type = e.target.value;
      this.bd = type;
      switch (type) {
        case "bind":
          this.getBind_recordlist();
          this.tags = true;
          break;
        case "replace":
          this.getReplace_record(); //获得替换记录表
          this.tags = false;
          break;
      }
    },
    //替换事件
    replaceHandler(s) {
      console.log(s);
      this.$refs.modalForm.add(s);
      this.$refs.modalForm["getRuleCodeValue"]
        ? this.$refs.modalForm.getRuleCodeValue()
        : "";
      this.$refs.modalForm.title = "替换";
      this.$refs.modalForm.disableSubmit = false;
    },
    //重新开始，清空输入框
    reload() {
      this.SN = "";
      this.finshed = 0;
      this.collectData = [];
      this.columnsData.map((item) => {
        item.result = false;
      });
      this.visible = false;
    },
    okRefresh() {
      this.getReplace_record();
      this.getBind_recordlist();
    },
    changeHandlerIpt(e) {},
    changicon(expand) {
      this.expand = expand;
    },
    changScan(e) {
      switch (this.order) {
        case 0:
          this.SN = this.scan;
          // this.getContainerInfo(this.scan);
          break;
        // case 1:
        //   this.$message.info("请扫描工牌");
        //   this.order = 2;
        //   break;
        // case 2:
        //   this.$message.info("请点击入周转区");
        //   this.order = 3;
        //   break;
        // default:
        //   break;
      }
    },
    config() {
      this.scan = "";
      this.order = 0;
      this.form = {};
      this.SN = "";
    },
    focus(e) {
      if (this.order === 0) {
        this.$message.info("请扫描关键物料条码");
      }
    },
  },
};
</script>
<style lang='less' scoped>
.containent {
  height: 100%;
  /deep/ .poros-card-body {
    height: 100%;
  }
  .wrap1 {
    flex-direction: column;
    display: flex;
    height: 100%;
    .topnav {
      display: flex;
      justify-content: space-between;
      .topsearch {
        flex: 1;
      }
      .btn_list {
        padding-top: 2px;
        padding-left: 24px;
      }
    }
  }
}
.content {
  flex: 1;
  display: flex;
  overflow: hidden;
  position: relative;
  .list1 {
    width: 340px;
    height: 100%;
  }
  .unshow {
    width: 0;
    padding-right: 0;
  }
  .icon {
    position: absolute;
    left: 308px;
    top: 50%;
    z-index: 5;
    width: 24px;
    height: 62px;
    margin-top: -31px;
    line-height: 62px;
    text-align: center;
    background-color: #f7f7f7;
    border-radius: 5px;
    border: 1px solid #ecedf0;
    cursor: pointer;
  }

  .tab {
    flex: 1;
    padding-left: 20px;
    display: flex;
    flex-direction: column;
    .bottom-form {
      flex: 1;
      height: 100%;
      overflow: hidden;
      .caiji {
        height: 100%;
        overflow: auto;
        border: 1px solid #eee;
        padding: 10px;
      }
      .bangding {
        height: 100%;
        overflow: auto;
        border: 1px solid #eee;
        padding: 10px;
      }
    }
    .left_list {
      height: 230px;
      border: 1px solid #eee;
      line-height: 40px;
      padding: 25px 20px;
    }
  }
}

/deep/.poros-alert-message {
  color: rgb(103, 194, 58);
  font-size: 18px;
}
.operator {
  margin-top: 30px;
}
.operator .poros-btn {
  float: right;
  margin-left: 10px;
}
.num {
  background: #409eff;
  height: 70px;
  margin-top: 20px;
  border-radius: 5px;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
.num .num_item {
  font-size: 20px;
  font-weight: 500;
  height: 30px;
}
.poros-tag {
  margin-right: 0;
}
.poros-form-inline {
  margin-bottom: 0;
}
.poros-alert {
  text-align: center;
}
</style>